package com.wangjw.tuling.netty.rpc.client;

import com.wangjw.tuling.netty.rpc.common.RpcDecode;
import com.wangjw.tuling.netty.rpc.common.RpcEncode;
import com.wangjw.tuling.netty.rpc.common.RpcRequest;
import com.wangjw.tuling.netty.rpc.common.RpcResponse;
import com.wangjw.tuling.netty.rpc.util.Serializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by wangjianwen on 2018/12/11.
 */
public class NettyClient {

    private static ConcurrentHashMap<String, SynchronousQueue<RpcResponse>> mapInfo = new ConcurrentHashMap<>();

    public static void putSynchronousQueue(String id, SynchronousQueue<RpcResponse> queue) {
        mapInfo.put(id, queue);
    }

    public static SynchronousQueue<RpcResponse> getSynchronousQueue(String id) {
        return mapInfo.get(id);
    }

    public static void removeById(String id) {
        mapInfo.remove(id);
    }

    public void sendRpcRequest(RpcRequest rpcRequest) throws Exception {
        try {
            channel.writeAndFlush(rpcRequest).sync();
        } catch (Exception e) {
            throw e;
        }
    }

    private Channel channel;

    public void init(String host, int port, Serializer serializer) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new RpcEncode(RpcRequest.class, serializer))
                                .addLast(new RpcDecode(RpcResponse.class, serializer))
                                .addLast(new NettyClientHandler());
                    }
                })
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, true);

        channel = bootstrap.connect(host, port).sync().channel();
        System.out.println("接口服务端连接成功");
    }

    public boolean isValidate() {
        if (channel != null) {
            return channel.isActive();
        }
        return false;
    }

    public void close() {
        if (channel != null && channel.isOpen()) {
            channel.close();
        }
    }
}
